<template>  
  <canvas ref="canvasRef" @mousedown="startDrawing" @mousemove="draw" @mouseup="stopDrawing" @mouseleave="stopDrawing" style="border: 1px solid black;"></canvas>  
</template>  
  
<script setup lang="ts">  
import { onMounted, ref, onUnmounted } from 'vue';  
  
// 引用canvas元素  
const canvasRef = ref<HTMLCanvasElement | null>(null);  
let ctx: CanvasRenderingContext2D | null = null;  
  
// 绘制状态  
let isDrawing = false;  
let startX = 0;  
let startY = 0;  
  
// 线条样式  
const lineWidth = ref(2);  
const lineColor = ref('black');  
  
// 初始化canvas和上下文  
onMounted(() => {  
  if (canvasRef.value) {  
    ctx = canvasRef.value.getContext('2d');  
    if (ctx) {  
      ctx.lineCap = 'round';  
    }  
  }  
});  
  
// 清理canvas（可选，如果需要在每次绘制前清除）  
function clearCanvas() {  
  if (ctx) {  
    ctx.clearRect(250, 250, canvasRef.value?.width ?? 10, canvasRef.value?.height ?? 10);  
  }  
}  
  
// 开始绘制  
function startDrawing(event: MouseEvent) {  
  isDrawing = true;  
  [startX, startY] = [event.offsetX, event.offsetY];  
}  
  
// 绘制  
function draw(event: MouseEvent) {  
  if (!isDrawing || !ctx) return;  
  clearCanvas(); // 如果需要每次绘制前清除，则取消注释此行  
  ctx.lineWidth = lineWidth.value;  
  ctx.strokeStyle = lineColor.value;  
  ctx.beginPath();  
  ctx.moveTo(startX, startY);  
  ctx.lineTo(event.offsetX, event.offsetY);  
  ctx.stroke();  
  [startX, startY] = [event.offsetX, event.offsetY];  
}  
  
// 停止绘制  
function stopDrawing() {  
  isDrawing = false;  
  // 可以在这里添加绘制结束后的处理  
}  
  
// 组件卸载时清理  
onUnmounted(() => {  
  ctx = null;  
});  
</script>  
  
<style scoped>  
canvas {  
  /* 其他样式 */  
}  
</style>